import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:amap_flutter_map/amap_flutter_map.dart';
import 'package:amap_flutter_base/amap_flutter_base.dart';
import 'package:xiaofanshu_flutter/config/amap_config.dart';
import 'package:xiaofanshu_flutter/model/pixel_art.dart';
import 'package:xiaofanshu_flutter/components/pixel_art_overlay.dart';
import 'package:xiaofanshu_flutter/pages/pixel_art/pixel_art_editor.dart';
import 'package:xiaofanshu_flutter/static/custom_color.dart';

/// 像素画地图示例页面
/// 展示如何在地图上显示和管理像素画
class PixelArtMapExample extends StatefulWidget {
  const PixelArtMapExample({super.key});

  @override
  State<PixelArtMapExample> createState() => _PixelArtMapExampleState();
}

class _PixelArtMapExampleState extends State<PixelArtMapExample> {
  AMapController? _mapController;
  double _currentZoom = 15.0;
  
  // 像素画列表（按 zIndex 排序显示）
  final RxList<PixelArt> _pixelArts = <PixelArt>[].obs;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('像素画地图'),
        backgroundColor: CustomColor.primaryColor,
        foregroundColor: Colors.white,
        actions: [
          IconButton(
            icon: const Icon(Icons.add),
            onPressed: _openPixelArtEditor,
            tooltip: '创建像素画',
          ),
        ],
      ),
      body: Stack(
        children: [
          // 地图
          AMapWidget(
            apiKey: const AMapApiKey(
              androidKey: AMapConfig.androidKey,
              iosKey: AMapConfig.iosKey,
            ),
            privacyStatement: const AMapPrivacyStatement(
              hasShow: true,
              hasAgree: true,
              hasContains: true,
            ),
            initialCameraPosition: const CameraPosition(
              target: LatLng(39.909187, 116.397451), // 北京
              zoom: 15,
            ),
            onMapCreated: (controller) {
              setState(() {
                _mapController = controller;
              });
              _loadPixelArts(); // 加载像素画数据
            },
            onCameraMove: (position) {
              setState(() {
                _currentZoom = position.zoom;
              });
            },
            onTap: (latLng) {
              // 点击地图创建像素画
              _showCreatePixelArtDialog(latLng);
            },
          ),
          
          // 像素画覆盖层
          if (_mapController != null)
            Obx(() => PixelArtManager(
              pixelArts: _pixelArts,
              mapController: _mapController!,
              currentZoom: _currentZoom,
              onPixelArtTap: _onPixelArtTap,
            )),
            
          // 图层管理面板
          Positioned(
            right: 10,
            bottom: 100,
            child: _buildLayerPanel(),
          ),
        ],
      ),
    );
  }

  /// 图层管理面板
  Widget _buildLayerPanel() {
    return Obx(() => Container(
      padding: const EdgeInsets.all(10),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(10),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 10,
          ),
        ],
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          const Text(
            '图层',
            style: TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 10),
          Text(
            '像素画: ${_pixelArts.length}',
            style: const TextStyle(fontSize: 12),
          ),
          const SizedBox(height: 5),
          Text(
            '缩放: ${_currentZoom.toStringAsFixed(1)}',
            style: const TextStyle(fontSize: 12),
          ),
        ],
      ),
    ));
  }

  /// 加载像素画数据
  void _loadPixelArts() {
    // TODO: 从服务器加载像素画数据
    // 这里使用模拟数据
    _pixelArts.value = [
      PixelArt(
        id: '1',
        userId: 1001,
        imageUrl: 'https://example.com/pixel_art_1.png',
        latitude: 39.909187,
        longitude: 116.397451,
        width: 100,
        height: 100,
        zIndex: 1,
        createTime: DateTime.now(),
        title: '示例像素画1',
      ),
      PixelArt(
        id: '2',
        userId: 1001,
        imageUrl: 'https://example.com/pixel_art_2.png',
        latitude: 39.910187,
        longitude: 116.398451,
        width: 200,
        height: 200,
        zIndex: 2,
        opacity: 0.8,
        createTime: DateTime.now(),
        title: '示例像素画2',
      ),
    ];
  }

  /// 打开像素画编辑器
  void _openPixelArtEditor() async {
    final result = await Get.to(() => const PixelArtEditorPage());
    if (result != null) {
      // TODO: 处理绘制结果，上传图片，保存到服务器
      Get.log('像素画创建结果: $result');
    }
  }

  /// 显示创建像素画对话框
  void _showCreatePixelArtDialog(LatLng latLng) {
    Get.dialog(
      AlertDialog(
        title: const Text('创建像素画'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('位置: ${latLng.latitude.toStringAsFixed(6)}, '
                '${latLng.longitude.toStringAsFixed(6)}'),
            const SizedBox(height: 20),
            const Text('选择创建方式：'),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () {
              Get.back();
              // TODO: 打开图片选择器
              _pickImageFromGallery(latLng);
            },
            child: const Text('上传图片'),
          ),
          TextButton(
            onPressed: () {
              Get.back();
              _openPixelArtEditorWithLocation(latLng);
            },
            child: const Text('手绘'),
          ),
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
        ],
      ),
    );
  }

  /// 从相册选择图片
  void _pickImageFromGallery(LatLng latLng) {
    // TODO: 使用 image_picker 选择图片
    // 1. 选择图片
    // 2. 确保图片有透明背景（可以提供背景移除功能）
    // 3. 上传到服务器
    // 4. 创建 PixelArt 对象
    Get.snackbar('提示', '图片选择功能待实现');
  }

  /// 打开像素画编辑器（带位置信息）
  void _openPixelArtEditorWithLocation(LatLng latLng) async {
    final result = await Get.to(() => const PixelArtEditorPage());
    if (result != null) {
      // TODO: 将绘制结果保存为图片并上传
      // 创建新的像素画
      final newPixelArt = PixelArt(
        id: DateTime.now().millisecondsSinceEpoch.toString(),
        userId: 1001, // TODO: 使用实际用户ID
        imageUrl: 'https://example.com/temp.png', // TODO: 使用上传后的URL
        latitude: latLng.latitude,
        longitude: latLng.longitude,
        width: result['size'],
        height: result['size'],
        zIndex: _pixelArts.length,
        createTime: DateTime.now(),
      );
      
      setState(() {
        _pixelArts.add(newPixelArt);
      });
    }
  }

  /// 点击像素画的处理
  void _onPixelArtTap(PixelArt pixelArt) {
    Get.bottomSheet(
      Container(
        padding: const EdgeInsets.all(20),
        decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20),
            topRight: Radius.circular(20),
          ),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              pixelArt.title ?? '未命名像素画',
              style: const TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 10),
            Text('创建时间: ${pixelArt.createTime.toString().split('.')[0]}'),
            Text('尺寸: ${pixelArt.width.toInt()}m × ${pixelArt.height.toInt()}m'),
            Text('层级: ${pixelArt.zIndex}'),
            const SizedBox(height: 20),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                ElevatedButton.icon(
                  onPressed: () {
                    Get.back();
                    // TODO: 编辑像素画
                  },
                  icon: const Icon(Icons.edit),
                  label: const Text('编辑'),
                ),
                ElevatedButton.icon(
                  onPressed: () {
                    Get.back();
                    _deletePixelArt(pixelArt);
                  },
                  icon: const Icon(Icons.delete),
                  label: const Text('删除'),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.red,
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 删除像素画
  void _deletePixelArt(PixelArt pixelArt) {
    Get.dialog(
      AlertDialog(
        title: const Text('确认删除'),
        content: const Text('确定要删除这个像素画吗？'),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              Get.back();
              setState(() {
                _pixelArts.removeWhere((p) => p.id == pixelArt.id);
              });
              // TODO: 从服务器删除
              Get.snackbar('成功', '像素画已删除');
            },
            child: const Text('删除', style: TextStyle(color: Colors.red)),
          ),
        ],
      ),
    );
  }
}

